var DB = require("../lib/db_mysql").DB;
var config = require('../lib/config');
var resErr = require('../lib/util.js').resErr;
var md5 = require('../lib/util.js').md5;
var async = require('async');
var moment = require('moment');
var http_request = require('../lib/util.js').http_request;

exports.leave = function(req, res) {
  var user_id = req.session.user_fw.user.id;
  var leave_type = req.param('leave_type');
  var begin_date = req.param('begin_date');
  var end_date = req.param('end_date');
  var reson = req.param('reson');
  var verify = req.param('verify');

  if (!leave_type) {
    return resErr(res,'请假类型不能为空！');
  }
  if (!begin_date) {
    return resErr(res,'开始时间不能为空！');
  }
  if (!end_date) {
    return resErr(res,'结束时间不能为空！');
  }
  if (!reson) {
    return resErr(res,'请假原因不能为空！');
  }
  var now = moment().format("YYYY-MM-DD HH:mm:ss");
  var params = [];
  params.push(leave_type);
  params.push(user_id);
  params.push(begin_date);
  params.push(end_date);
  params.push(reson);
  var db = new DB();
  var teacher_id;
  var teacher_name;
  async.waterfall([
    function(cb) { //获取对应的老师ID
      var tmp_params = [];
      // t_user 学生表
      // t_class 查询对应的审批老师
      // t_department 查询对应的教导主任
      // sql_text = "select a.team_leader as teacher_id,a.team_leadername as teacher_name  from t_group as a,t_group_user as b where a.id=b.group_id and b.user_id=?;";
      var sql_text = " select u.id,u.name,u.location_id,cc.* from t_user u ";
      sql_text += " left join (select c.*,s1.user_realname teacher_name,dd.director_name,dd.director_id";
      sql_text += " from t_class c ";
      sql_text += " left join (select d.department_id,d.director_id,s2.user_realname as director_name from t_department  d,t_sys_user s2  where d.director_id = s2.user_id) dd ";
      sql_text += " on c.department_id = dd.department_id";
      sql_text += " inner join t_sys_user s1";
      sql_text += " where c.teacher_id = s1.user_id) cc";
      sql_text += " on u.class = cc.class_id";
      sql_text += " where u.id = ?";
      tmp_params.push(user_id);
      db.queryMap(sql_text, tmp_params, function(err, data) {
        if (err) return cb(err);
        if (data && data.teacher_id > 0) {
          teacher_id = data.teacher_id
          teacher_name = data.teacher_name
        } else {
          //console.log(Mysql.sql);
          return cb('找不到对应审批老师信息');
        }
        return cb(null);
      })
    } //这里需要加判断逻辑，如重复请假，请假时间冲突等
  ], function(err) {
    if (err) return resErr(res, err);
    sql_text = "insert into t_leave set leave_type=?,user_id=?,begin_date=?,end_date=?,status=0,reson=?,verify_by=?,verify_name = ?,create_date=?";
    if (verify){
      params.push(verify);
    }else{
      params.push(teacher_id);
      params.push(teacher_name);
    }
    params.push(now);
    db.query(sql_text, params, function(err, datas) {
      if (err) {
        return resErr(res, err);
      }
      return res.json({
        "success": true
      })
    })
  })
}


exports.leavelist_student = function(req, res) {
  var user_id = req.session.user_fw.user.id;
  var status = req.param('status');
  var params = [];

  //var sql_text = "select * from t_leave where user_id=? ";
  var sql_text =""
  sql_text = "select a.*,b.name,d.id_desc as leave_desc ,e.id_desc as status_desc from t_leave as a, t_user as b ,t_flag_desc as d,t_flag_desc as e  where a.user_id=?  and a.user_id = b.id and (d.flagtype=2 and d.id=a.leave_type) and (e.flagtype=1 and e.id=a.status) ";
  params.push(user_id);
  if (status) {
    sql_text += " and a.status = ?";
    params.push(status);
  }
  sql_text += " order by create_date desc";
  var db = new DB();
  db.query(sql_text, params, function(err, datas) {
    if (err) return resErr(res, err);
    return res.jsonp(datas);
  });
}

exports.leavelist_teacherold = function(req, res) {
  var user_id = req.session.user_fw.user.id;
  var status = req.param('status');
  var params = [];
  params.push(user_id);
  params.push(user_id);
  params.push(user_id);

  var sql_text = "select a.*,b.name,c.user_realname as verify from t_leave as a ,t_user as b,t_sys_user as c where (a.verify_by=? or a.verify_by2 = ?) and a.user_id = b.id and  c.user_id=?";
  if (status) {
    sql_text += " and status = ?";
    params.push(status);
  }
  sql_text += " order by create_date desc";
  var db = new DB();
  db.query(sql_text, params, function(err, datas) {
    if (err) return resErr(res, err);
    return res.jsonp(datas);
  });
}


exports.leavelist_teacher = function(req,res){

  var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
  var page  = parseInt(req.param("page") || req.param("pageNum") || '1');

  //var user_id = req.session.user_fw.user.id;
  var user_id = req.session.adminuser.user_id;
  var status = req.param('status');
  var params = [];

  //var sql_text = "select a.*,b.name,c.user_realname as verify from t_leave as a ,t_user as b,t_sys_user as c where (a.verify_by=? or a.verify_by2 = ?) and a.user_id = b.id and  c.user_id=?";
  var sql_text = "select a.*,b.name,d.id_desc as leave_desc ,e.id_desc as status_desc  ";
  sql_text += " from t_leave as a ,t_user b,t_flag_desc as d,t_flag_desc as e ";
  sql_text += " where 1 = 1 ";
  sql_text += " and a.user_id = b.id ";
  sql_text += " and  (a.leave_type=d.id and d.flagtype=2) and (a.status=e.id and e.flagtype=1) ";

  if(req.session.adminuser.role.role_key == 'admin'){

  }else {
    sql_text += " and (a.verify_by=? or a.verify_by2 = ?) ";
    params.push(user_id);
    params.push(user_id);
  }


  
 

  if (status) {
    sql_text += " and status = ?";
    params.push(status);
  }
  sql_text += " order by a.id "; 
  var db = new DB();


  db.queryPage(sql_text,params,page,limit,function(err,result){
    if(err) return resErr(res, err);
    return res.json(result);
  });

};

exports.leave_list = function(req,res){

    var sql_text = "SELECT u.* FROM t_leave u WHERE status=0";
    var tmp_params = [];
    
    var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
    var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
    if(req.param("sort")){
        sql_text += " order by u." + req.param("sort");
        if(req.param("dir")){
            sql_text += " " + req.param("dir");
        }
    }
    
    var db = new DB();
    db.queryPage(sql_text,tmp_params,page,limit,function(err,result){
        if(err) return resErr(res, err);

        console.log(result);
        return res.json(result);
    });
};


exports.leave_reject = function(req,res){
  var id = req.param('id');
  var user_id = req.session.adminuser.user_id;
  if(!id) return res.json({success:false,msg:'用户ID不能为空！'});
  var verify_comment = req.param('verify_comment');
  if(!verify_comment) return res.json({success:false,msg:'拒绝事由不能为空！'});
  var db = new DB();
  async.waterfall([
    function(cb){
      var sql_text = "select * from t_leave where id = ?";
      db.queryMap(sql_text,[id],function(err,data){
        if(err){
          return cb(err);
        }
        if(!data){
          return cb("无法找到该记录！");
        }
        if(data.status != "0"){
          return cb("该记录已经被审批，操作失败！");
        }
        if(data.verify_by != user_id){
          return cb("审批老师不符合，操作失败！");
        }
        return cb(null);
      })
    },function(cb){
      
      var tmp_params = [];
      var sql_text = "update t_leave set verify_comment=?,verify_date=now() ";
      tmp_params.push(verify_comment);
      
      sql_text += ",status=2";
      sql_text += " where id=?";
      tmp_params.push(id);

      
      db.query(sql_text,tmp_params,function(err,datas){
        if(err){
          return cb(err);
        }
        return cb(null);
      });
    }
  ],function(err){
    if(err){
      return resErr(res,err);
    }else{
      return res.json({success: true, msg: '审批成功'});
    }
  })




}

exports.leave_approval = function(req,res){
  var id = req.param('id');

  if(!id) return res.json({success: false, msg: '请假流水ID不能为空'});
  var user_id = req.session.adminuser.user_id;
  var db = new DB();

  
  async.waterfall([
    function(cb){
      var sql_text = "select * from t_leave where id = ?";
      db.queryMap(sql_text,[id],function(err,data){
        if(err){
          return cb(err);
        }
        if(!data){
          return cb("无法找到该记录！");
        }
        if(data.status != "0"){
          return cb("该记录已经被审批，操作失败！");
        }
        if(data.verify_by != user_id){
          return cb("审批老师不符合，操作失败！");
        }
        return cb(null);
      })
    },function(cb){
      var tmp_params = [];
      var sql_text = "update t_leave set verify_comment=?,verify_date=now() ";
      var verify_comment = '同意';
      tmp_params.push(verify_comment);
      sql_text += ",status=1";
      sql_text += " where id=?";
      tmp_params.push(id);
      db.query(sql_text, tmp_params, function(err, datas){
        if(err){
          cb(err)
        }
        return cb(null);
      });
    }
  ],function(err){
    if(err){
      return resErr(res,err);
    }else{
      return res.json({success: true, msg: '审批成功'});
    }
  })
 
}
